package com.mobile_fault_detector.controller;

import com.mobile_fault_detector.service.IKeywordEventService;
import com.mobile_fault_detector.utils.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 关键词事件控制器
 */
@Slf4j
@RestController
@RequiredArgsConstructor
public class KeywordEventController {

    private final IKeywordEventService IKeywordEventService;

    /**
     * 根据关键词查询埋点事件并获取AI回答
     * @param request 关键词查询请求
     * @return AI回答响应
     */
//    @PostMapping("/keyword/getAnswer")
//    public Result getAnswerByKeyword(@RequestBody KeywordQueryRequest request) {
//        try {
//            // 参数验证
//            if (request == null || request.getAnswer() == null || request.getAnswer().trim().isEmpty()) {
//                return Result.fail("查询关键词不能为空");
//            }
//
//            log.info("收到关键词查询请求: {}", request.getAnswer());
//            return keywordEventService.getAnswerByKeyword(request);
//        } catch (Exception e) {
//            log.error("根据关键词查询埋点事件并获取AI回答失败，关键词: {}, 异常信息: {}",
//                    request != null ? request.getAnswer() : "null", e.getMessage(), e);
//            return Result.fail("根据关键词查询埋点事件并获取AI回答失败");
//        }
//    }

    /**
     * 根据用户问题获取AI回答
     * 先调用AI接口获取关键词，再调用getAnswerByKeyword方法获取最终答案
     *
     * @param query 用户问题
     * @return AI回答响应
     */
    @PostMapping("/session/getAnswer")
    public Result getAnswer(@RequestBody String query) {
        try {
            // 参数验证
            if (query == null || query.trim().isEmpty()) {
                return Result.fail("用户问题不能为空");
            }
            //记录操作开始时间
            long startTime = System.currentTimeMillis();
            log.info("Operation started at: " + startTime);
            Result result = IKeywordEventService.getAnswer(query);
            //记录操作结束时间
            long endTime = System.currentTimeMillis();
            log.info("Operation end at: " + endTime);
            log.info("cost time: " + (endTime - startTime) + "ms");
            return result;
        } catch (Exception e) {
            log.error("根据用户问题获取AI回答失败，问题: {}, 异常信息: {}", query, e.getMessage(), e);
            return Result.fail("获取AI回答失败");
        }
    }
}